<?php

declare(strict_types=1);

namespace App\Controller;

use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Annotation\AutoController;
use App\Controller\BaseController;
use App\Model\User;
use App\Model\Order;

#[AutoController]
class UserController extends BaseController
{
    public function index(RequestInterface $request)
    {
        return "Hello World User";
    }

    //注册
    public function register(RequestInterface $request)
    {
        $nickname = $request->input('nickname');
        $username = $request->input('username');
        $password = $request->input('password');
        $vpassword = $request->input('vpassword');

        // 参数过滤，确保只包含字母、数字和特定字符
        $nickname = filter_var($nickname, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        $username = filter_var($username, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
    
        if (empty($nickname) || empty($username) || empty($password) || empty($vpassword)) {
            $data['err'] = 1;
            $data['msg'] = '参数不能为空';
            return json_encode($data);
        }
        if (!preg_match('/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/', $username) || !preg_match('/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/', $vpassword)) {
            $data['err'] = 1;
            $data['msg'] = '账号密码至少一个数字和一个英文字母，6~20字';
            return json_encode($data);
        }
        if (!preg_match('/^.{1,10}$/', $nickname)) {
            $data['err'] = 1;
            $data['msg'] = '昵称，1~10字';
            return json_encode($data);
        }
        if ($password !== $vpassword) {
            $data['err'] = 1;
            $data['msg'] = '密码和验证密码不一致';
            return json_encode($data);
        }
        if ($this->isRepeat($username)) {
            $data['err'] = 1;
            $data['msg'] = '账号已存在';
            return json_encode($data);
        }

        $user = new User();
        $user->username = $username;
        $user->nickname = $nickname;
        $user->secretKey = bin2hex(random_bytes(16));
        $hashedPassword = hash('sha256', md5($password.$user->secretKey).$user->secretKey);
        $user->password = $hashedPassword;
        $res = $user->save();
        if ($res) {
            $data['err'] = 0;
            $data['msg'] = '注册成功';
            $data['username'] = $username;
        } else {
            $data['err'] = 1;
            $data['msg'] = '注册失败';
        }
        return json_encode($data);
    }

    //检查账号是否重复
    private function isRepeat($username)
    {
        $userInfo = User::query()->where('username', $username)->first();
        return $userInfo;
    }
  
    //登录
    public function login(RequestInterface $request)
    {
        $username = $request->input('username');
        $password = $request->input('password');

        // 参数过滤，确保只包含字母、数字和特定字符
        $username = filter_var($username, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        $password = filter_var($password, FILTER_SANITIZE_FULL_SPECIAL_CHARS);
        
        if (empty($username)) {
            $data['err'] = 1;
            $data['msg'] = '账号不能为空';
            return json_encode($data);
        }
        if (empty($password)) {
            $data['err'] = 1;
            $data['msg'] = '密码不能为空';
            return json_encode($data);
        }

        $userInfo = User::where('username', $username)->first();
        if (empty($userInfo)) {
            $data['err'] = 1;
            $data['msg'] = '账号不存在';
            return json_encode($data);
        }
        
        $password = hash('sha256', md5($password.$userInfo->secretKey).$userInfo->secretKey);
        if ($password !== $userInfo->password) {
            $data['err'] = 1;
            $data['msg'] = '密码错误';
            return json_encode($data);
        }

        $token = hash('sha256', uniqid() . time());
        $userInfo->login_at = date('Y-m-d H:i:s', time());
        $userInfo->token = $token;
        $userInfo->tokenExpiration = date('Y-m-d H:i:s', time()+60*60*24);
        $res = $userInfo->save();
        if ($res) {
            $data['err'] = 0;
            $data['msg'] = '登录成功';
            $data['user']['token'] = $token;
            $data['user']['id'] = $userInfo->id;
            $data['user']['nickname'] = $userInfo->nickname;
            $data['user']['username'] = $userInfo->username;
        } else {
            $data['err'] = 1;
            $data['msg'] = '登录失败';
        }
        return json_encode($data);
    }
    
    //获取用户资料
    public function getUser(RequestInterface $request)
    {
        $isAuth = $this->Auth($request, 1);
        $AuthInfo = json_decode($isAuth, true);
        if ($AuthInfo['err'] === 0) {
            $orderNum = Order::query()->where('user_id', $AuthInfo['id'])->count();
            $data['err'] = 0;
            $data['msg'] = '获取成功';
            $data['orderNum'] = $orderNum;
            $data['balance'] = $AuthInfo['balance'];
            $data['nickname'] = $AuthInfo['nickname'];
        } else {
            $data['err'] = 1;
            $data['msg'] = '认证失败，重新登录';
        }
        return json_encode($data);
    }
    
    public function editUser(RequestInterface $request)
    {
        $userId = $request->input('userId');
        $nickName = $request->input('nickname');
        if (!$userId) {
            $data['err'] = 1;
            $data['msg'] = '参数错误';
            return json_encode($data);
        }
        
        if (!preg_match('/^.{1,10}$/', $nickName)) {
            $data['err'] = 1;
            $data['msg'] = '昵称，1~10字';
            return json_encode($data);
        }
        
        $isAuth = $this->Auth($request, 0);
        $AuthInfo = json_decode($isAuth, true);
        if ($AuthInfo['err'] === 0) {
            $user = User::query()->find($userId);
            $user->nickname = $nickName;
            $res = $user->save();
            if ($res) {
                $data['err'] = 0;
                $data['msg'] = '修改成功';
            } else {
                $data['err'] = 1;
                $data['msg'] = '修改失败，请稍后重试';
            }
        } else {
            $data['err'] = 2;
            $data['msg'] = '认证失败，重新登录';
        }
        return json_encode($data);
    }

    //自动所有人登录
    public function loginTogether()
    {
        $userList = User::query()->get();
        foreach ($userList as $k => $v) {
            $token = hash('sha256', uniqid() . time());
            $login_at = date('Y-m-d H:i:s', time());
            $tokenExpiration = date('Y-m-d H:i:s', time()+60*60*24);
            User::query()->where('id', $v['id'])->update(['token' => $token,'login_at' => $login_at,'tokenExpiration' => $tokenExpiration]);
        }
        $data['err'] = 0;
        $data['msg'] = '登录成功';
        return json_encode($data);
    }
}
